package org.linlinjava.litemall.db.util;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;

public class HttpUtil {

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param picUrl
     *            发送请求的URL
     * @return String 所代表远程资源的响应结果
     */
    public static JSONObject sendGet(String picUrl) {
        String baseUrl = "https://www.moderatecontent.com/api/v2?face=true&key=14b2f599adfddb15a1940c346fd77c55&url=";
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = baseUrl + picUrl;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return JSONObject.parseObject(result.toString());
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        System.out.println(sendGet("http://192.144.180.108:1456/litemall/wx/storage/fetch/zyo4uc6l69cj5a2hh0uc.jpg"));
        System.out.println("cost Time :" + (System.currentTimeMillis() - startTime));
    }

}
